//
//  RechargeViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/10.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "WithdrawDepositViewController.h"
#import "BankWithdrawDepositViewController.h"

@interface WithdrawDepositViewController ()<UITextFieldDelegate>
@property (nonatomic, strong)UITextField * moneyTextField;//充值
@property (nonatomic, assign) BOOL isHaveDian;

@property (nonatomic, assign) BOOL isFirstZero;
@end

@implementation WithdrawDepositViewController(networking)
//提现
- (void)rechargeData{
    //    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"reMoney":self.moneyTextField.text,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"reMoney":self.moneyTextField.text,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/userCent/rechargeDo"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                BankWithdrawDepositViewController * vc = [[BankWithdrawDepositViewController alloc] init];
                vc.webURLStr = [jsonData[@"body"] objectForKey:@"shabaction"];
                vc.bankNeedInfoDic = @{
                                       @"merchantNo":[jsonData[@"body"] objectForKey:@"merchantNo"],
                                       @"keyEnc":[jsonData[@"body"] objectForKey:@"keyEnc"],
                                       @"merOrderNo":[jsonData[@"body"] objectForKey:@"merOrderNo"],
                                       @"jsonEnc":[jsonData[@"body"] objectForKey:@"jsonEnc"],
                                       @"sign":[jsonData[@"body"] objectForKey:@"sign"]};
                vc.sessionID = jsonData[@"session"];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
@end
@implementation WithdrawDepositViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"账户余额提现";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setUpViews];//构造控件
}

- (void)setUpViews{
    UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 16/WIDTH_6_SCALE, 150/WIDTH_6_SCALE, 13/WIDTH_6_SCALE)];
    [self label:titleLab withFont:DEF_FontSize_14 withText:@"请输入充值金额(元)" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.view];
    UILabel * symbolLab = [[UILabel alloc] initWithFrame:CGRectMake(titleLab.left, titleLab.bottom + 47/WIDTH_6_SCALE, 17/WIDTH_6_SCALE, 22/WIDTH_6_SCALE)];
    //    symbolLab.backgroundColor = [UIColor orangeColor];
    symbolLab.text = @"￥";
    symbolLab.textColor = [UIColor orangeColor];
    [self.view addSubview:symbolLab];
    //充值
    self.moneyTextField = [[UITextField alloc] initWithFrame:CGRectMake(symbolLab.right + 8/WIDTH_6_SCALE, symbolLab.top, SCREEN_WIDTH - symbolLab.right - 18/WIDTH_6_SCALE - 5/WIDTH_6_SCALE, symbolLab.height)];
    self.moneyTextField.font = [UIFont systemFontOfSize:25.0];
    self.moneyTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.moneyTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.moneyTextField.delegate = self;
    [self.view addSubview:self.moneyTextField];
    //分割线
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, self.moneyTextField.bottom + 10/WIDTH_6_SCALE, SCREEN_WIDTH - (18*2)/WIDTH_6_SCALE, 1/WIDTH_6_SCALE)];
    lineView.backgroundColor = getColor(grayBGColor);
    [self.view addSubview:lineView];
    //下一步
    UIButton * nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(28/WIDTH_6_SCALE, lineView.bottom + 55/WIDTH_6_SCALE, SCREEN_WIDTH - (28*2)/WIDTH_6_SCALE, 38/WIDTH_6_SCALE)];
    [nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    nextBtn.titleLabel.font = DEF_FontSize_14;
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self button:nextBtn withBGColor:[UIColor orangeColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:6 withMasksToBounds:YES withViwe:self.view];
}
#pragma mark - action
- (void)nextBtnClick:(UIButton *)sender{
    NSLog(@"下一步");
    if (self.moneyTextField.text == nil || [self.moneyTextField.text isEqualToString:@""] || [self.moneyTextField.text length] == 0) {
        ShowMessage(@"请填写具体数额");
        return;
    }
    [self rechargeData];
}
#pragma mark - textfieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.moneyTextField) {
        if ([textField.text rangeOfString:@"."].location==NSNotFound) {
            _isHaveDian = NO;
        }
        if ([textField.text rangeOfString:@"0"].location==NSNotFound) {
            _isFirstZero = NO;
        }
        if ([string length]>0){
            unichar single=[string characterAtIndex:0];//当前输入的字符
            //数据格式正确
            if ((single >='0' && single<='9') || single=='.'){
                if([textField.text length]==0){
                    if(single == '.'){
                        //首字母不能为小数点
                        return NO;
                    }
                    if (single == '0') {
                        _isFirstZero = YES;
                        return YES;
                    }
                }
                if (single=='.'){
                    //text中还没有小数点
                    if(!_isHaveDian){
                        _isHaveDian=YES;
                        return YES;
                    }else{
                        return NO;
                    }
                }else if(single=='0'){
                    if ((_isFirstZero&&_isHaveDian)||(!_isFirstZero&&_isHaveDian)) {
                        //首位有0有.（0.01）或首位没0有.（10200.00）可输入两位数的0
                        if([textField.text isEqualToString:@"0.0"]){
                            return NO;
                        }
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt=(int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if (_isFirstZero&&!_isHaveDian){
                        //首位有0没.不能再输入0
                        return NO;
                    }else{
                        return YES;
                    }
                }else{
                    if (_isHaveDian){
                        //存在小数点，保留两位小数
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt= (int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if(_isFirstZero&&!_isHaveDian){
                        //首位有0没点
                        return NO;
                    }else{
                        return YES;
                    }
                }
            }else{
                //输入的数据格式不正确
                return NO;
            }
        }else{
            return YES;
        }
    }return YES;
}

@end
